<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
		<meta name="viewport" content="width=device-width, initial-scale=1.0">
		<meta http-equiv="Access-Control-Allow-Origin" content="*">
		<title> </title>
		<link rel="stylesheet" href="css/common.css">
	</head>
	<style>
		[v-cloak]{
		display: none !important;
	}
</style>
	<body>
		<!-- <div class="h20 bgHeader"></div> -->
		<div id="app" v-cloak>
			<div class="header plr15 flex alcenter bgHeader white fixed pt30">
				<img src="../../static/image/return.png" class="h15 wt15 mr20" @click="goback" />
				<div class="white ft18 bold ">{{symbol}}</div>
			</div>
			<div>
				<div class="pt60 pb10 plr20  bgHeader" style="min-height: 50px;">
					<div class="flex alcenter between pt5">
						<div class="" :class="[updown<0?'red':'green']">
							<p class="bold ft24">{{newprice || '0.00'}}</p>
							<p class="mt10">{{updown*100 | toFixed2}}%</p>
						</div>
						<div class="w50">
							<div class="flex between mb5">
								<span class="blue">{{translatedInfo.high || '--'}}</span>
								<span class="blue white">{{maxprice || '0.00'}}</span>
							</div>
							<div class="flex between mb5">
								<span class="blue">{{translatedInfo.low || '--'}}</span>
								<span class="blue white">{{minprice ||'0.00'}}</span>
							</div>
							<div class="flex between">
								<span class="blue">{{translatedInfo.volume || '--'}}</span>
								<span class="blue white">{{dayvom ||'0.00'}}</span>
							</div>
						</div>
					</div>
				</div>
				<div id="tv_chart_container" style="width:100%;height:60vh;margin-top: 5px;"></div>
				<div class="mt5 pb100  bgHeader">
					<div class="plr10">
						<div class="flex alcenter ptb5 ft12">
							<div class="flex1 ">{{translatedInfo.num || '--'}}</div>
							<div class="flex1 tc">{{translatedInfo.price || '--'}}</div>
							<div class="flex1 tr">{{translatedInfo.time || '--'}}</div>
						</div>
						<div class="">
							<div class="flex alcenter ptb5" :class="[item.direction=='BUY'?'red':'green']" v-for="(item,i) in complete" :key="i">
								<div class="flex1">{{item.amount |fixed4}}</div>
								<div class="flex1 tc">{{item.price}}</div>
								<div class="flex1 tr">{{item.time |formatDate}}</div>
							</div>
						</div>
					</div>
				</div>
				<div class="flex between plr20 alcenter plr20 bgHeader fixed w100 pos_l0b0" v-if="type!='lever'" style="height: 80px;">
					<!-- <span>添加自选</span>
				<img src="./images/collect.png" style="width: 20px;" id="noCollct" v-if="!hasCollcet" @click="triggerCollcet(true)">
				<img src="./images/collect_active.png" style="width: 20px;"  id="hasCollct" @click="triggerCollcet(false)" v-else > -->
					<button class="goTranbuy bgRed flex1 ptb10 mr20 white radius4" @click="goTrade('buy')">{{translatedInfo.buy || '--'}}</button>
					<button class="goTransell bgGreen flex1 ptb10 white radius4" @click="goTrade('sell')">{{translatedInfo.sell || '--'}}</button>
				</div>
			</div>
		</div>
		<script type="text/javascript" src="https://js.cdn.aliyun.dcloud.net.cn/dev/uni-app/uni.webview.1.5.2.js"></script>
		<script src="lib/vue.min.js"></script>

		<script src="lib/jquery.js"></script>
		<!-- <script src="javascripts/jquery.cookie.js"></script> -->
		<script src="lib/layer_mobile/layer.js"></script>
		<script src="javascripts/main.js"></script>
		<script src="javascripts/socket.io.js"></script>
		<script src="tradeview/charting_library/charting_library.min.js"></script>
		<script>
			document.addEventListener('UniAppJSBridgeReady', function() {
				// document.querySelector('.btn-list').addEventListener('click', function(evt) {
				// 	uni.navigateBack({
				// 		delta: 1
				// 	});
				// });
				var vm = new Vue({
					el: '#app',
					data: {
						widget: null,
						symbolInfo: null,
						feed: null,
						wsEx: null,
						ws: null,
						lists: [],
						newData: '',
						symbol: '',
						priceScale: 100000,
						histime: '',
						newprice: '0.00',
						updown: '0.00',
						maxprice: '0.00',
						minprice: '0.00',
						dayvom: '0.00',
						currencyList: [],
						couponSelected: '',
						legal_id: '',
						currency_id: '',
						legal_name: '',
						currency_name: '',
						currency_match_id:'',
						hasCollcet: '',
						myid: '',
						balance: '',
						rates: '',
						websockUrl: 'wss://www.hotbull.co', //'ws://www.nncstar.xyz/ws'
						url: 'https://www.hotbull.co',
						complete: [],
						transwords: {
							zh: {
								high: '高',
								low: '低',
								volume: '24H量',
								num: '数量',
								price: '价格',
								time: '时间',
								buy: '买入',
								sell: '卖出',
							},
							en: {
								high: 'high',
								low: 'low',
								volume: '24H volume',
								num: 'number',
								price: 'price',
								time: 'time',
								buy: 'buy',
								sell: 'sell',
							},
							hk: {
								high: '高',
								low: '低',
								volume: '24H量',
								num: '數量',
								price: '價格',
								time: '時間',
								buy: '買入',
								sell: '賣出',
							},
							jp: {
								high: '高さ',
								low: '低い',
								volume: '24 h量',
								num: '数',
								price: '価格',
								time: '時間',
								buy: '購入',
								sell: '売却',
							},
							ar:{
								high: 'مرتفع',
								low: 'منخفض',
								volume: '24مقدار',
								num: 'كمية',
								price: 'ثمن',
								time: 'زمان',
								buy: 'شراء',
								sell: 'بيع',
							}
						},
						translatedInfo: {},
						lang: '',
						type:''
					},
					filters:{
						fixed4:function(vals){
							var values = iTofixed(vals,4);
							return values;
						},
						toFixed2: function(vals) {
							var values = iTofixed(vals,2);
							return values;
						},
						formatDate: function (value) {
							let date = new Date(value);
							let y = date.getFullYear();
							let MM = date.getMonth() + 1;
							MM = MM < 10 ? ('0' + MM) : MM;
							let d = date.getDate();
							d = d < 10 ? ('0' + d) : d;
							let h = date.getHours();
							h = h < 10 ? ('0' + h) : h;
							let m = date.getMinutes();
							m = m < 10 ? ('0' + m) : m;
							let s = date.getSeconds();
							s = s < 10 ? ('0' + s) : s;
							return h + ':' + m + ':' + s;
						 }
					},
					created() {
						var that = this;
						if(window.plus){	
							that.lang = plus.storage.getItem('lang') || 'zh';
						}else{
							// that.lang = JSON.parse(localStorage.getItem('lang')).data;
							that.lang = localStorage.getItem('lang') || 'zh';
						}
						var paramsed = get_all_params();
						that.symbol = paramsed.symbol;
						let c_name = paramsed.symbol.split('/')
						that.legal_name = c_name[1];
						that.currency_name = c_name[0];
						that.legal_id = paramsed.legal_id;
						that.currency_id = paramsed.currency_id;
						that.currency_match_id = paramsed.currency_match_id;
						that.type = paramsed.type || '';
						// console.log(that.$t('market.volume'));
						// console.log(localStorage.getItem('mytrade'))
						that.translatedInfo = that.transwords[that.lang];
						// console.log(that.translatedInfo);
						// document.getElementById('mytitle').innerText='123';
						document.title = that.symbol;
						
						// if(window.plus){							
						// 	if (!plus.storage.getItem('token')) {
						// 		uni.navigateTo({
						// 			url: '/pages/mine/login',
							
						// 		});
						// 	}
						// }else{
						// 	if (localStorage.getItem('token') == null || localStorage.getItem('token') == '') {
						// 		uni.navigateTo({
						// 			url: '/pages/mine/login',
						// 		});
						// 	}
							
						// }
						// if (!plus.storage.getItem('token')) {
						// 	uni.navigateTo({
						// 		url: '/pages/mine/login',

						// 	});
						// }
						// uni.setNavigationBarColor({ 
						// 			frontColor: '#ffffff',
						// backgroundColor: '#ff0000',})
						// plus.navigator.setStatusBarStyle('black');
						// plus.navigator.setStatusBarBackground('#102030');
						that.getrate();
					},
					computed: {
						listenState() { //监听交易对
							return this.symbol;
						}
					},
					watch: {
						listenState: function(a, b) { //监听交易对
							if (a != b && b != '') {
								this.widget.setSymbol(a, localStorage.getItem('tim'), function onReadyCallback() {}) //切换币种
							}
						}
					},
					mounted() {
						this.createWidget();
						this.getComplete();
					},
					destroyed() {
						this.removeWidget();
					},
					beforeDestroy() {

					},
					methods: {
						getrate(){
						    let that = this;
							initDataToken({
								url: '/market/symbol-thumb',
								data:{
									
								}
							}, function (res) {
								let data = res;
								let symbol = this.get_all_params().symbol;
								for (let i = 0; i < res.length; i++) {
									let coin = res[i];
									if (coin.symbol == symbol) {
										// this.form.buy.limitPrice = this.form.sell.limitPrice = coin.price;
										that.dayvom	= Number(coin.volume).toFixed(4)
										that.maxprice = coin.high
										that.minprice = coin.low	
										that.newprice = coin.close
										that.updown = coin.chg
										// console.log(111111111111111111);
									}
								}
								
							})
						},
						goback() {
							if(window.plus){
								console.log('back999999999999')
								uni.navigateBack({
									delta: 1
								});
							}else{
								history.back(-1);
							}
						},
						goTrade(mytype) {
							// layer_msg('Not yet open!');
							// return;
							if (this.symbol === 'IOT/USDT') return
							// console.log(this.symbol)
							
							let localData = {
								symbol: this.symbol
							}
							
								
							if(localData.symbol == 'VAC/USDT' && mytype == 'buy'){
								uni.navigateTo({
								    url: '/pages/exchange/index'
								});
								return ;
							}
							console.log('asffffffffffffffffffffffff');
							if(window.plus){
								console.log('+++++++++------9991')								
								plus.storage.setItem('tradeData', JSON.stringify(localData));
								console.log(JSON.stringify(localData)+'*8*8')
								plus.storage.setItem('tradeType', mytype);
							}else{
								console.log('+++++++++------999')
								localStorage.setItem('tradeData', JSON.stringify(localData));
								console.log(JSON.stringify(localData)+'*8*8')
								localStorage.setItem('tradeType', mytype);
							}
							// plus.storage.setItem('tradeData', JSON.stringify(localData));
							// plus.storage.setItem('tradeType', mytype);
							// uni.switchTab({
							// 	url: '/pages/trade/trade'
							// })
							uni.navigateTo({
							    url: '/pages/trade/trade'
							});
						},
						getComplete() {
							initDataToken({
								url: '/market/latest-trade',
								type: 'POST',
								data: {
									symbol: this.symbol,
									size: 20,
								}
							}, res => {
								this.complete = res;
								this.completeSocket();
								// console.log(JSON.stringify(res.complete))
							})
						},

						// 收藏
						triggerCollcet(e) {
							// if(e){
							// 	this.initDataToken({url:'quotation/collect',data:{match_id:this.myid},type:'POST'},(res)=>{
							// 		alert(res);
							// 		this.hasCollcet=true;
							// 	}) 
							// }else{
							// 	this.initDataToken({url:'quotation/remove',data:{match_id:this.myid}},(res,msg)=>{
							// 		this.hasCollcet=false;
							// 	}) 
							// }
						},
						timestampToTime(timestamp) {
							var time=''
							if(timestamp.toString().length>11){
								time=timestamp
							}else{
								time=timestamp*1000
							}
							var now = new Date(time),
					 　　	y = now.getFullYear(),
					 　　	m = now.getMonth() + 1,
					　　	d = now.getDate();
					 　　	return y + "-" + (m < 10 ? "0" + m : m) + "-" + (d < 10 ? "0" + d : d) + " " + now.toTimeString().substr(0, 8);
						},

						// 默认
						connect(real) { //封装推送数据
							var that = this;
							var websock = new WebSocket(that.websockUrl);
							websock.onopen = function() {
								// console.log(that.symbol+'111111111111');
								websock.send(JSON.stringify({
									"type": "sub",
									params: "KLINE." + that.symbol
								}))
								websock.send(JSON.stringify({type: "sub", params: "DAY_MARKET"}))
								websock.send(JSON.stringify({type: "sub", params: "GLOBAL_TX."+ that.symbol}))
							}
							websock.onmessage = function(msg) {
								// console.log(JSON.stringify(msg.data)+'kline');
								// console.log(typeof msg.data)
								var msg=JSON.parse(msg.data);
								let type = localStorage.getItem('type')
								var resmsg = msg;
								if (resmsg.type == 'KLINE') {
									let obj = {}
									// console.log(that.symbol );
									// console.log(resmsg.symbol)
									if (that.symbol == resmsg.symbol) {
										let data = resmsg.kline;
										// console.log(JSON.stringify(data))
										// console.log(type,data.period)
										if (data.period == type) {
											obj.open = Number(data.open)
											obj.low = Number(data.low)
											obj.high = Number(data.high)
											obj.close = Number(data.close)
											obj.volume = Number(data.amount)
											obj.time = Number(data.time)
											real(obj)
										}
									}
								}
								
								// console.log(JSON.stringify(resmsg))
								if(resmsg.type=='DAY_MARKET'){
									// console.log(JSON.stringify(resmsg)+'DAY_MARKET')
									// console.log(resmsg.symbol)
									// console.log(that.symbol)
									if (that.symbol == resmsg.symbol) {
										// console.log('-------------------------')
										let datas  = resmsg.quotation;
										// if (data.period == '1day') {
											that.newprice = datas.close;
											that.maxprice = datas.high;
											that.minprice = datas.low;
											that.dayvom = Number(datas.amount).toFixed(4);
											that.updown = datas.change;
										// }
										
									}
								}
								
								if(resmsg.type=='GLOBAL_TX'){
									var comdata=resmsg.completes;
									for(var i in comdata){
										comdata[i].time=that.timestampToTime(comdata[i].timestamp).substr(11)
										that.complete.unshift(comdata[i])
									}
									that.complete.slice(0,30);
									if (that.complete.length > 30) {
										that.complete.pop()
									}
									// console.log(JSON.stringify(that.complete))
		                        }
							}
						},
						// 币币交易全站交易WebSocket
						completeSocket() { //封装推送数据
							var that = this;
							var websock = new WebSocket(that.websockUrl);
							if(window.plus){
								var tokens = plus.storage.getItem('token');
								console.log(tokens)
							}else{
								// var tokens = JSON.parse(localStorage.getItem('token')).data;
								var tokens = localStorage.getItem('token');
							}
							
							websock.onopen = function() {
								websock.send(JSON.stringify({
									type: "sub",
									params: "match_trade." + that.symbol
								}))
							}
							websock.onmessage = function(msg) {
								var msg = JSON.parse(msg.data);
								if (msg.type == 'match_trade') {
									if (that.symbol == msg.symbol) {
										var times = that.timestampToTime(msg.data[0].ts)
										var way;
										msg.data[0].direction == 'buy' ? way = 1 : way = 2;
										var data = {
											price: msg.data[0].price,
											time: times,
											number: msg.data[0].amount,
											way: way
										}
										that.complete.unshift(data);
										
										if (that.complete.length > 20) {
											that.complete.pop()
										}
									}

								}
							}
						},
						createWidget() {
							let _this = this;
							let lang;
							if(window.plus){
								lang = plus.storage.getItem('lang') || 'zh';
							}else{
								lang = localStorage.getItem('lang') || 'zh';
							}
							if(lang=='hk'){
								lang = 'zh_TW'
							}else if(lang=='jp'){
								lang = 'ja'
							}
							this.$nextTick(function() {
								let widget = _this.widget = new TradingView.widget({
									symbol: _this.symbol,
									interval: 1,
									debug: true,
									fullscreen: false,
									autosize: true,
									container_id: "tv_chart_container",
									// datafeed: new Datafeeds.UDFCompatibleDatafeed("http://demo_feed.tradingview.com"),
									datafeed: _this.createFeed(),
									library_path: "tradeview/charting_library/",
									custom_css_url: 'bundles/new.css',
									locale: lang,
									width: "100%",
									height: 516,
									drawings_access: {
										type: 'black',
										tools: [{
											name: "Regression Trend"
										}]
									},
									disabled_features: [ //  禁用的功能
										'left_toolbar', 'widget_logo', 'header_saveload', 'compare_symbol', 'display_market_status',
										'go_to_date', 'header_chart_type', 'header_compare', 'header_interval_dialog_button',
										'header_resolutions', 'header_screenshot', 'header_symbol_search', 'header_undo_redo',
										'legend_context_menu', 'show_hide_button_in_legend', 'show_interval_dialog_on_key_press',
										'snapshot_trading_drawings', 'symbol_info', 'timeframes_toolbar', 'use_localstorage_for_settings',
										'volume_force_overlay'
									],
									enabled_features: [ //  启用的功能（备注：disable_resolution_rebuild 功能用于控制当时间范围为1个月时，日期刻度是否都是每个月1号
										'dont_show_boolean_study_arguments', 'hide_last_na_study_output', 'move_logo_to_main_pane',
										'same_data_requery', 'side_toolbar_in_fullscreen_mode', 'disable_resolution_rebuild'
									],
									charts_storage_url: 'http://saveload.tradingview.com',
									charts_storage_api_version: "1.1",
									toolbar_bg: "transparent",
									timezone: "Asia/Shanghai",
									studies_overrides: {
										'volume.precision': '1000'
									},
									overrides: _this.overrides()
								});

								widget.MAStudies = [];
								widget.selectedIntervalButton = null;
								// widget.setLanguage('en')
								widget.onChartReady(function() { //图表方法
									// document.getElementById('trade-view').childNodes[0].setAttribute('style', 'display:block;width:100%;height:100%;');
									//let that =this

									widget.chart().createStudy('Moving Average', false, true, [15, 'close', 0], null, {
										'Plot.color': '#e843da'
									});
									widget.chart().createStudy("MA Cross", false, false, [10, 20]);

									let buttonArr = [{
											value: "1min",
											period: "1",
											text: "Time",
											chartType: 3,
											type: "1min"
										},
										{
											value: "1",
											period: "1m",
											text: "1min",
											chartType: 1,
											type: "1min"
										},
										{
											value: "5",
											period: "5m",
											text: "5min",
											chartType: 1,
											type: "5min"
										},
										{
											value: "30",
											period: "30m",
											text: "30min",
											chartType: 1,
											type: "30min"
										},
										{
											value: "60",
											period: "60分钟",
											text: "1hour",
											chartType: 1,
											type: "60min"
										},
										{
											value: "1D",
											period: "1D",
											text: "1day",
											chartType: 1,
											type: "1day"
										},
										{
											value: "1W",
											period: "1W",
											text: "1week",
											chartType: 1,
											type: "1week"
										},
										{
											value: "1M",
											period: "1M",
											text: "1mon",
											chartType: 1,
											type: "1mon"
										}
									];
									let btn = {};
									let nowTime = '';
									buttonArr.forEach((v, i) => {
										let button = widget.createButton()
										button.attr('title', v.text)
											.addClass("my2")
											.text(v.text)

										if (v.text == '1min') {
											button.css({
												'color': '#218bde',
												'border-bottom': '1px solid #218bde'
											})
											localStorage.setItem('tim', '1min') //默认为1分钟
											localStorage.setItem('type', '1min') //默认为1分钟
										}
										btn = button.on("click", function(e) {
											$(this).parents(".left").children().find(".my2").removeAttr("style"); //去掉1分钟的
											handleClick(e, v.value, v.type);

											widget.chart().setChartType(v.chartType); //改变K线类型
										});


									});
									if (localStorage.getItem('tim') == '1min') {
										widget.chart().setChartType(1);
									}
									let handleClick = (e, value, type) => {
										_this.setSymbol = function(symbol, value) {
											gh.chart().setSymbol(symbol, value);
										};
										localStorage.setItem('tim', value);
										localStorage.setItem('type', type) //默认为1分钟
										widget.chart().setResolution(value, function onReadyCallback() {}); //改变分辨率

										$(e.target)
											.addClass("mydate")
											.closest("div.space-single")
											.siblings("div.space-single")
											.find("div.button")
											.removeClass("mydate")
									};
								});
								_this.widget = widget;
							})
						},
						createFeed() {
							let this_vue = this;
							let Datafeed = {};
							Datafeed.DataPulseUpdater = function(datafeed, updateFrequency) {
								this._datafeed = datafeed;
								this._subscribers = {};

								this._requestsPending = 0;
								var that = this;

								var update = function() {
									if (that._requestsPending > 0) {
										return;
									}

									for (var listenerGUID in that._subscribers) {
										var subscriptionRecord = that._subscribers[listenerGUID];
										var resolution = subscriptionRecord.resolution;

										var datesRangeRight = parseInt((new Date().valueOf()) / 1000);


										//	BEWARE: please note we really need 2 bars, not the only last one
										//	see the explanation below. `10` is the `large enough` value to work around holidays
										var datesRangeLeft = datesRangeRight - that.periodLengthSeconds(resolution, 10);

										that._requestsPending++;

										(function(_subscriptionRecord) { // eslint-disable-line
											that._datafeed.getBars(_subscriptionRecord.symbolInfo, resolution, datesRangeLeft, datesRangeRight,
												function(bars) {
													that._requestsPending--;

													//	means the subscription was cancelled while waiting for data
													if (!that._subscribers.hasOwnProperty(listenerGUID)) {
														return;
													}

													if (bars.length === 0) {
														return;
													}

													var lastBar = bars[bars.length - 1];
													if (!isNaN(_subscriptionRecord.lastBarTime) && lastBar.time < _subscriptionRecord.lastBarTime) {
														return;
													}

													var subscribers = _subscriptionRecord.listeners;

													//	BEWARE: this one isn't working when first update comes and this update makes a new bar. In this case
													//	_subscriptionRecord.lastBarTime = NaN
													var isNewBar = !isNaN(_subscriptionRecord.lastBarTime) && lastBar.time > _subscriptionRecord.lastBarTime;

													//	Pulse updating may miss some trades data (ie, if pulse period = 10 secods and new bar is started 5 seconds later after the last update, the
													//	old bar's last 5 seconds trades will be lost). Thus, at fist we should broadcast old bar updates when it's ready.
													if (isNewBar) {
														if (bars.length < 2) {
															throw new Error('Not enough bars in history for proper pulse update. Need at least 2.');
														}

														var previousBar = bars[bars.length - 2];
														for (var i = 0; i < subscribers.length; ++i) {
															subscribers[i](previousBar);
														}
													}

													_subscriptionRecord.lastBarTime = lastBar.time;

													for (var i = 0; i < subscribers.length; ++i) {
														subscribers[i](lastBar);
													}
												},

												//	on error
												function() {
													that._requestsPending--;
												});
										})(subscriptionRecord);
									}
								};

								if (typeof updateFrequency != 'undefined' && updateFrequency > 0) {
									setInterval(update, updateFrequency);
								}
							};

							Datafeed.DataPulseUpdater.prototype.periodLengthSeconds = function(resolution, requiredPeriodsCount) {
								var daysCount = 0;

								if (resolution === 'D') {
									daysCount = requiredPeriodsCount;
								} else if (resolution === 'M') {
									daysCount = 31 * requiredPeriodsCount;
								} else if (resolution === 'W') {
									daysCount = 7 * requiredPeriodsCount;
								} else {
									daysCount = requiredPeriodsCount * resolution / (24 * 60);
								}

								return daysCount * 24 * 60 * 60;
							};

							Datafeed.DataPulseUpdater.prototype.subscribeDataListener = function(symbolInfo, resolution, newDataCallback,
								listenerGUID) {
								this._datafeed._logMessage('Subscribing ' + listenerGUID);

								if (!this._subscribers.hasOwnProperty(listenerGUID)) {
									this._subscribers[listenerGUID] = {
										symbolInfo: symbolInfo,
										resolution: resolution,
										lastBarTime: NaN,
										listeners: []
									};
								}

								this._subscribers[listenerGUID].listeners.push(newDataCallback);
							};

							Datafeed.DataPulseUpdater.prototype.unsubscribeDataListener = function(listenerGUID) {
								this._datafeed._logMessage('Unsubscribing ' + listenerGUID);
								delete this._subscribers[listenerGUID];
							};

							Datafeed.Container = function(updateFrequency) {
								this._configuration = {
									supports_search: false,
									supports_group_request: false,
									supported_resolutions: ['1', '3', '5', '15', '30', '60', '120', '240', '360', '720', '1D', '3D', '1W',
										'1M'
									],
									supports_marks: true,
									supports_timescale_marks: true,
									exchanges: ['gh']
								};

								this._barsPulseUpdater = new Datafeed.DataPulseUpdater(this, updateFrequency || 10 * 1000);
								// this._quotesPulseUpdater = new Datafeed.QuotesPulseUpdater(this);

								this._enableLogging = true;
								this._callbacks = {};

								this._initializationFinished = true;
								this._fireEvent('initialized');
								this._fireEvent('configuration_ready');
							};

							Datafeed.Container.prototype._fireEvent = function(event, argument) {
								if (this._callbacks.hasOwnProperty(event)) {
									var callbacksChain = this._callbacks[event];
									for (var i = 0; i < callbacksChain.length; ++i) {
										callbacksChain[i](argument);
									}

									this._callbacks[event] = [];
								}
							};

							Datafeed.Container.prototype._logMessage = function(message) {
								if (this._enableLogging) {
									var now = new Date();
								}
							};

							Datafeed.Container.prototype.on = function(event, callback) {
								if (!this._callbacks.hasOwnProperty(event)) {
									this._callbacks[event] = [];
								}

								this._callbacks[event].push(callback);
								return this;
							};

							Datafeed.Container.prototype.onReady = function(callback) {
								let that = this;
								if (this._configuration) {
									setTimeout(function() {
										callback(that._configuration);
									}, 0);
								} else {
									this.on('configuration_ready', function() {
										callback(that._configuration);
									});
								}
							};

							Datafeed.Container.prototype.resolveSymbol = function(symbolName, onSymbolResolvedCallback,
								onResolveErrorCallback) {
								this._logMessage("GOWNO :: resolve symbol " + symbolName);
								Promise.resolve().then(() => {


									// this._logMessage("GOWNO :: onResultReady inject "+'AAPL');
									onSymbolResolvedCallback({
										"name": this_vue.symbol,
										"timezone": "Asia/Shanghai",
										"pricescale": this_vue.priceScale,
										"minmov": 1, //minmov(最小波动), pricescale(价格精度), minmove2, fractional(分数)
										"minmov2": 0, //这是一个神奇的数字来格式化复杂情况下的价格。
										"ticker": this_vue.symbol,
										"description": "",
										"type": "bitcoin",
										"volume_precision": 8,
										// "exchange-traded": "sdt",
										// "exchange-listed": "sdt",
										//现在，这两个字段都为某个交易所的略称。将被显示在图表的图例中，以表示此商品。目前此字段不用于其他目的。
										"has_intraday": true,
										"has_weekly_and_monthly": true,
										"has_no_volume": false, //布尔表示商品是否拥有成交量数据。
										'session': '24x7',
										'supported_resolutions': ['1', '3', '5', '15', '30', '60', '120', '240', '360', '720', '1D', '3D',
											'1W',
											'1M'
										]

									});
								})
							};


							//初始化数据
							Datafeed.Container.prototype.getBars = function(symbolInfo, resolution, rangeStartDate, rangeEndDate,
								onHistoryCallback, onErrorCallback) {
								// if (rangeStartDate > 0 && (rangeStartDate + '').length > 10) {
								//   throw new Error(['Got a JS time instead of Unix one.', rangeStartDate, rangeEndDate]);
								// }

								// if (resolution.indexOf('D') == -1 && resolution.indexOf('W') == -1 && resolution.indexOf('M') == -1) {
								// 	resolution = resolution
								// } else if (resolution.indexOf('W') != -1 || resolution.indexOf('M') != -1) {
								// 	resolution = resolution
								// }
								// if(resolution=='1D'){
								// 	resolution='1day'
								// }
								// if(resolution=='1W'){
								// 	 resolution='1week'
								// }
								// if(resolution=='1M'){
								// 	 resolution='1mon'
								// }
								// console.log(rangeStartDate);
								// console.log(rangeEndDate)
								// console.log(resolution);
								// console.log(JSON.stringify(symbolInfo) ) 
								rangeStartDate = rangeStartDate *1000;
								rangeEndDate = rangeEndDate *1000;
								$.ajax({
									url: this_vue.url + '/market/history?' + 'from=' + rangeStartDate + '&to=' + rangeEndDate +
										'&symbol=' + this_vue.symbol + '&resolution=' + resolution,
									type: 'get',
									success: function(res) {
										// console.log(res)
										// console.log(JSON.stringify(res))
										//bars.push({time:item[0],open:item[1],high:item[2],low:item[3],close:item[4],volume:item[5]})
										var bars = [];
										if (res&& res.length > 0) {
											res.forEach((item, i) => {
                                                 bars.push({time:item[0],open:item[1],high:item[2],low:item[3],close:item[4],volume:item[5]})
											})
											
											var noData = bars.length == 0;
											var retBars = onHistoryCallback(bars,{noData:true});
										}
										if (!res || res.length <= 0) {
											console.log('af');
											onHistoryCallback([], {
												noData: true
											})
										}
									}
								})

							};
							//实时数据
							Datafeed.Container.prototype.subscribeBars = function(symbolInfo, resolution, onRealtimeCallback,
								listenerGUID,
								onResetCacheNeededCallback) {
								this_vue.connect(onRealtimeCallback)
								this._barsPulseUpdater.subscribeDataListener(symbolInfo, resolution, onRealtimeCallback, listenerGUID, onResetCacheNeededCallback);
							};

							Datafeed.Container.prototype.unsubscribeBars = function(listenerGUID) {

								this._barsPulseUpdater.unsubscribeDataListener(listenerGUID);

							};

							return new Datafeed.Container;
						},

						updateWidget(item) {
							this.symbolInfo = {
								name: item,
								ticker: item,
								description: "",
								session: "24x7",
								supported_resolutions: ['1', '5', '30', '60', '240', '1D', '3D', '1W', '1M'],
								has_intraday: true,
								has_daily: true,
								has_weekly_and_monthly: true,
								timezone: "UTC",
							}
							this.removeWidget();
							this.createWidget();
						},
						removeWidget() {
							if (this.widget) {
								this.widget.remove();
								this.widget = null;
							}
						},
						overrides() {
							let style = {
								up: "#02C289",
								down: "#e86d43",
								bg: "#131f30",
								grid: "#1E2740",
								cross: "#1E2740",
								border: "#4e5b85",
								text: "#61688A",
								areatop: "rgba(122, 152, 247, .1)",
								areadown: "rgba(122, 152, 247, .02)"
							};
							return {
								'volumePaneSize': "small", //large, medium, small, tiny
								'paneProperties.topMargin': '20',
								"scalesProperties.lineColor": style.bg,
								"scalesProperties.textColor": style.text,
								"paneProperties.background": style.bg, //改变背景色的重要代码
								"paneProperties.vertGridProperties.color": style.grid,
								"paneProperties.horzGridProperties.color": style.grid,
								"paneProperties.crossHairProperties.color": style.cross,
								"paneProperties.legendProperties.showLegend": true,
								"paneProperties.legendProperties.showStudyArguments": true,
								"paneProperties.legendProperties.showStudyTitles": true,
								"paneProperties.legendProperties.showStudyValues": true,
								"paneProperties.legendProperties.showSeriesTitle": true,
								"paneProperties.legendProperties.showSeriesOHLC": true,
								"mainSeriesProperties.candleStyle.upColor": style.up,
								"mainSeriesProperties.candleStyle.downColor": style.down,
								"mainSeriesProperties.candleStyle.drawWick": true,
								"mainSeriesProperties.candleStyle.drawBorder": true,
								"mainSeriesProperties.candleStyle.borderColor": style.border,
								"mainSeriesProperties.candleStyle.borderUpColor": style.up,
								"mainSeriesProperties.candleStyle.borderDownColor": style.down,
								"mainSeriesProperties.candleStyle.wickUpColor": style.up,
								"mainSeriesProperties.candleStyle.wickDownColor": style.down,
								"mainSeriesProperties.candleStyle.barColorsOnPrevClose": false,
								"mainSeriesProperties.hollowCandleStyle.upColor": style.up,
								"mainSeriesProperties.hollowCandleStyle.downColor": style.down,

								"mainSeriesProperties.hollowCandleStyle.drawWick": true,
								"mainSeriesProperties.hollowCandleStyle.drawBorder": true,
								"mainSeriesProperties.hollowCandleStyle.borderColor": style.border,
								"mainSeriesProperties.hollowCandleStyle.borderUpColor": style.up,
								"mainSeriesProperties.hollowCandleStyle.borderDownColor": style.down,
								"mainSeriesProperties.hollowCandleStyle.wickColor": style.line,
								"mainSeriesProperties.haStyle.upColor": style.up,
								"mainSeriesProperties.haStyle.downColor": style.down,
								"mainSeriesProperties.haStyle.drawWick": true,
								"mainSeriesProperties.haStyle.drawBorder": true,
								"mainSeriesProperties.haStyle.borderColor": style.border,
								"mainSeriesProperties.haStyle.borderUpColor": style.up,
								"mainSeriesProperties.haStyle.borderDownColor": style.down,
								"mainSeriesProperties.haStyle.wickColor": style.border,
								"mainSeriesProperties.haStyle.barColorsOnPrevClose": false,
								"mainSeriesProperties.barStyle.upColor": style.up,
								"mainSeriesProperties.barStyle.downColor": style.down,
								"mainSeriesProperties.barStyle.barColorsOnPrevClose": false,
								"mainSeriesProperties.barStyle.dontDrawOpen": false,
								"mainSeriesProperties.lineStyle.color": style.border,
								"mainSeriesProperties.lineStyle.linewidth": 1,
								"mainSeriesProperties.lineStyle.priceSource": "close",
								"mainSeriesProperties.areaStyle.color1": style.areatop,
								"mainSeriesProperties.areaStyle.color2": style.areadown,
								"mainSeriesProperties.areaStyle.linecolor": style.borders,
								"mainSeriesProperties.areaStyle.linewidth": 1,
								"mainSeriesProperties.areaStyle.priceSource": "close"
							}
						},
						chose() {
							this.widget.setLanguage('en') //设置语言
						}
					},
				})
			})
		</script>
	</body>

</html>
